<template>
  <el-container>
    <el-aside width="258px">
      <side_tree :data="userDept" :type="'dept'" :default="groupData.deptId" :typeName="'部门管理'" @childtofather="treeNode" />
    </el-aside>
    <el-main>
      <el-col :span="24" class="flex flex-justify clear" style="border-bottom: 1px solid #eee;padding-bottom: 10px">
        <!--名称-->
        <h1>{{groupData.deptName}}</h1>
        <!--按钮-->
        <el-col :span="18" class="flex flex-right">
          <el-button v-if="roleIdList.includes(2)" size="small" type="warning" @click="add(groupData.parentIds)" style="margin-right:20px">
            <i class="fa fa-plus"></i> 创建部门</el-button>
          <el-button v-if="roleIdList.includes(3)" size="small" @click="chson('edit')" :disabled="!isUpdate" type="info">
            <i class="fa fa-edit"></i> 修改
          </el-button>
          <el-button v-if="roleIdList.includes(4)" size="small" type="danger" @click="del">
            <i class="fa fa-trash-o"></i>
            删除</el-button>
        </el-col>
      </el-col>
      <!--部门信息 表单-->
      <el-form size="small" class="from-box" ref="groupData" :rules="rules" :model="groupData" label-width="80px">
        <el-col :span="6">
          <el-form-item label="简称" prop="deptName">
            <el-input :readonly="isUpdate" v-model="groupData.deptName"></el-input>
          </el-form-item>
          <el-form-item label="所属分部" prop="parentIds">
            <el-cascader :disabled="isUpdate" :options="userDept" change-on-select :props="propFather" v-model="groupData.parentIds"
              :show-all-levels="false" style="width: 100%">
            </el-cascader>
          </el-form-item>
          <el-form-item label="部门类型" prop="deptType">
            <el-select v-model="groupData.deptType" :disabled="isUpdate" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="deptOrder">
            <el-input-number v-model="groupData.deptOrder" :disabled="isUpdate" controls-position="right" :min="1" :max="9" style="width: 100%"></el-input-number>
          </el-form-item>
          <el-form-item label="部门描述" prop="deptDesc">
            <el-input v-model="groupData.deptDesc" :disabled="isUpdate" type="textarea" :rows="2"></el-input>
          </el-form-item>
          <el-form-item label="部门ID" prop="id">
            <el-input disabled v-model="groupData.deptId"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="flex flex-justify clear" v-if="show" style="border-top: 1px solid #eee;padding-top: 20px">
          <!--按钮-->
          <el-col :span="18" class="flex flex-left">
            <el-button size="small" @click="chson('save',groupData.deptId)" type="primary">
              <i class="fa fa-save"></i> 保存
            </el-button>
            <el-button size="small" @click="chson('cancel',groupData.deptId)">
              <i class="fa fa-trash-o"></i> 取消</el-button>
          </el-col>
        </el-col>
      </el-form>
      <AddModal :addVal="addVal" :treeData="userDept" :options="options" @closeModal="closeModal" @finish="finish" />
    </el-main>
  </el-container>
</template>
<script>
  import side_tree from "../aside";
  import AddModal from "./addModal";
  import ElCol from "element-ui/packages/col/src/col";
  import {
    formCheck,
    trim,
    deepClone
  } from '../../../lib/utils';
  import {
    departmentManagement
  } from "../../../service/service_zbw";
  import {
    mapState,
    mapActions
  } from "vuex";
  export default {
    components: {
      //创建树组件
      ElCol,
      side_tree,
      AddModal
    },
    data() {
      //设备名称校验
      const checkName = (rule, value, callback) => {
        let str = trim(value);
        if (!str) {
          return callback(new Error('简称不能为空'));
        } else {
          callback();
        }
      };
      //所属分布校验
      const checkFatherNode = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请选择所属分部'));
        } else {
          if (value.length <= 0) {
            callback(new Error('请选择所属分部'));
          }
          callback();
        }
      };
      return {
        //判断是否是编辑
        isUpdate: true,
        show: false,
        //默认联动选择
        propFather: {
          value: 'deptId',
          label: 'deptName'
        },
        //右侧数据
        groupData: {
          deptName: '',
          parentIds: [],
          deptOrder: 1,
          deptType: 2,
          deptDesc: '',
          deptId: 0,
        },
        copyGroupData: {},
        //校验规则
        rules: {
          deptName: [{
              required: true,
              message: '请输入简称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }
          ],
          deptOrder: [{
            required: true,
          }],
          deptType: [{
            required: true,
          }],
          deptDesc: [{
              message: '请输入部门描述',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度在 1 到 50 个字符',
              trigger: 'blur'
            }
          ]
        },
        options: [{
          value: 1,
          label: '实体部门'
        }, {
          value: 2,
          label: '虚拟部门'
        }],
        addVal: {
          show: false,
          fatherNode: '',
        },
      }
    },
    computed: {
      ...mapState({
        userDept: state => state.userDept,
        roleIdList: state => state.roleIdList,
      }),
    },
    methods: {
      ...mapActions([
        'GetUserDept',
        'GetUserRealDept'
      ]),
      /**@function
       * 页面初始化
       */
      init() {
        this.groupData = deepClone(this.userDept[0]);
      },
      /**@function
       * 操作完成
       */
      operateFinish() {
        this.GetUserDept();
        this.GetUserRealDept();
      },
      //接收树组件传递过来的数据，obj是节点对象
      treeNode(obj) {
        //赋值给data
        this.groupData = deepClone(obj);
        console.log(obj)
        if (this.groupData.deptType === 2) {
          this.groupData.deptName = this.groupData.deptName.substring(0, this.groupData.deptName.length - 4);
          console.log(this.groupData.deptName)
        }
        this.isUpdate = true;
        this.show = false;
        console.log(this.groupData)
      },

      /**
       *
       */
      beforeOperate(id) {
        if (!id) {
          this.$message.warning('请选择您要操作的节点');
          return;
        }
      },
      //编辑，保存，修改
      async chson(val, id) {
        //this.beforeOperate(id);
        if (val == 'edit') {
          //修改开始， 备份原始数据
          this.copyGroupData = deepClone(this.groupData);
          this.changeButtonStatus();
        } else if (val == 'cancel') {
          this.handleReset('groupData');
          //取消时,还原数据，消除操作痕迹
          this.groupData = null;
          this.groupData = deepClone(this.copyGroupData);
          this.changeButtonStatus();
        } else if (val == 'save') {
          let flag = formCheck(this, 'groupData');
          if (flag) {
            let param = {
              deptName: this.groupData.deptName,
              //parentIds: this.groupData.parentIds,
              parentId: this.groupData.parentIds[this.groupData.parentIds.length - 1],
              deptOrder: this.groupData.deptOrder,
              deptDesc: this.groupData.deptDesc,
              deptId: this.groupData.deptId,
              deptType: this.groupData.deptType
            };
            let res = await departmentManagement.update(param);
            if (res.success) {
              this.operateFinish();
              this.$message({
                type: 'success',
                message: res.msg
              });
              this.changeButtonStatus();
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              });
            }
          }
        }
      },
      /**@function
       *
       */
      changeButtonStatus() {
        this.isUpdate = !this.isUpdate;
        this.show = !this.show;
      },
      //删除
      del() {
        this.isUpdate = true;
        this.show = false;
        this.$confirm('您确定要删除部门“' + this.groupData.deptName + '”吗？', '询问', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.delete();
        }).catch(() => {
          //TODO
        });
      },
      async delete() {
        // if (this.groupData.children) {
        //   this.$message({
        //     type: 'warning',
        //     message: '该部门下有子部门，请先删除子部门'
        //   });
        //   return;
        // }
        let param = this.groupData.deptId;
        let res = await departmentManagement.del(param);
        if (res.success) {
          this.operateFinish();
          this.groupData = deepClone(this.userDept[0]);
          this.$message({
            type: 'success',
            message: res.msg
          });
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      },
      //新增
      add(val) {
        this.isUpdate = true;
        this.show = false;
        this.addVal.show = true;
        this.addVal.fatherNode = this.groupData.fatherNode;
      },
      /**@function
       * 新增完成
       */
      finish(val) {
        if (val.parentIds === null) {
          val.parentIds = [];
        }
        this.groupData = deepClone(val);
        // if (this.groupData.deptType === 2) {
        //   this.groupData.deptName = this.groupData.deptName.substring(0, this.groupData.deptName.length - 4);
        //   console.log('this.groupData.deptName--------------',this.groupData.deptName)
        // }
        this.operateFinish();
      },
      /**
       * 关闭模态框
       */
      closeModal(val) {
        this.addVal.show = false;
      },
      /**
       * 清空表单
       */
      handleReset(name) {
        this.$refs[name].resetFields();
      }
    },
    watch: {
      "groupData.deptId" (newval, oldval) {
        this.isUpdate = true;
      }
    },
    mounted() {
      this.init();
    },
  }

</script>

<style scoped>
  h1 {
    width: 25%;
    font-weight: bold;
    color: #666666;
    font-size: 18px;
  }

</style>

